package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.model.common.article.es.vo.SearchArticleVo;
import com.zhentao.model.common.dtos.ResponseResult;
//import com.zhentao.pojo.ApArticle;
import com.zhentao.model.common.dtos.ApArticle;
import com.zhentao.service.ApArticleService;
import com.zhentao.mapper.ApArticleMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
* @author EWEWW
* @description 针对表【ap_article(文章信息表，存储已发布的文章)】的数据库操作Service实现
* @createDate 2024-06-25 14:39:50
*/
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle>
    implements ApArticleService{
  @Autowired
  private RestHighLevelClient client;
  @Autowired
  private ApArticleMapper articleMapper;
  @Override
  public ResponseResult esInit() throws IOException {
    //1.查询出需要导入es的文章
    List<ApArticle> apArticleList = articleMapper.selectList(null);

    //2.批量导入es
    BulkRequest bulkRequest = new BulkRequest("app_info_article");
    for (ApArticle article : apArticleList) {
      SearchArticleVo searchArticleVo = new SearchArticleVo();
      BeanUtils.copyProperties(article,searchArticleVo);
      String json = JSON.toJSONString(searchArticleVo);
      IndexRequest indexRequest = new IndexRequest().id(searchArticleVo.getId()+"").source(json, XContentType.JSON);
      bulkRequest.add(indexRequest);
    }
    client.bulk(bulkRequest, RequestOptions.DEFAULT);

      return ResponseResult.okResult("导入成功："+apArticleList.size());
  }
}




